package com.ocean.stack;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/next-greater-element-i/
 */
public class NextGreaterElementI {
    public static void main(String[] args) {
        // nums1 = [4,1,2], nums2 = [1,3,4,2].
        // nums1 = [2,4], nums2 = [1,2,3,4].
        int[] nums1 = {2, 4};
        int[] nums2 = {1, 2, 3, 4};
        NextGreaterElementI greaterElementI = new NextGreaterElementI();
        int[] ints = greaterElementI.nextGreaterElement(nums1, nums2);
        System.out.println(Arrays.toString(ints));
        int[] ints1 = greaterElementI.nextGreaterElement2(nums1, nums2);
        System.out.println(Arrays.toString(ints1));

    }

    /**
     * 暴力求解
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int[] ret = new int[l1];
        for (int i = 0; i < l1; i++) {
            int item = nums1[i];
            // 找到相等的
            int k = 0;
            while (k < l2 && nums2[k] != item) {
                k++;
            }
            // 找下一个大的
            int j = k + 1;
            while (j < l2 && nums2[j] < item) {
                j++;
            }
            ret[i] = j < l2 ? nums2[j] : -1;
        }
        return ret;
    }


    public int[] nextGreaterElement2(int[] nums1, int[] nums2) {
        // 遍历num2 将每个位置的下一个大的数 用hashMap存下来
        Stack<Integer> stack = new Stack<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = nums2.length - 1; i >= 0; i--) {
            int item = nums2[i];
            while (!stack.isEmpty() && stack.peek() < item) {
                stack.pop();
            }
            map.put(item, stack.isEmpty() ? -1 : stack.peek());
            stack.push(item);
        }
        int[] ret = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            ret[i] = map.get(nums1[i]);
        }
        return ret;
    }
}
